from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from .serializers import LoginSerializer, UserSerializer
from datetime import datetime
from .authentications import generate_jwt
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from .serializers import ResetPwdSerializer


class LoginView(APIView):
    # 用于登入
    def post(self, request):
        # 1.验证数据是否可用
        # 创建 LoginSerializer 实例，传入请求数据。
        serializer = LoginSerializer(data=request.data)
        # 2.调用 is_valid 方法验证数据
        if serializer.is_valid():
            # 3.调用 validate 方法获取验证结果
            user = serializer.validated_data.get('user')
            # 更新最后登录时间
            user.last_login = datetime.now()
            # 保存用户信息
            user.save()
            # 生成JWT token
            token = generate_jwt(user)
            # 4.返回响应，包含 token
            return Response({'token': token, 'user': UserSerializer(user).data}) # 调用UserSerializer(user).data是为了序列化user对象  返回一个字典
        else:
            # 5.如果验证失败，返回错误信息
            # print(serializer.errors)
            # 返回400状态码，表示请求参数错误
            # person = ｛"username": "张三", "age": 18｝
            # person.values() = ['战三', 18]  返回对象 dict_values
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail": detail}, status=status.HTTP_400_BAD_REQUEST)


class ResetPwdView(APIView):
    # permission_classes = [IsAuthenticated]   除掉login不需要验证其他都需要

    def post(self, request):
        # request,是DRF封装的  ，  rest_framework.request.Request
        # 这个对象是针对django的HttpRequest对象进行的封装
        # print(request)
        # print(request.user)
        #
        # context 是 自己想要传递的其他参数
        serializer = ResetPwdSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data.get('pwd1')
            request.user.set_password(pwd1)
            request.user.save()
            return Response()
        else:
            print(serializer.errors,"=====>")
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail": detail}, status=status.HTTP_400_BAD_REQUEST)
